﻿using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using 纺织贸易管理系统;

namespace BLL
{
    public static class 销售发货单BLL
    {
        public static void 保存单据(DanjuTable danju, List<danjumingxitable> danjumingxitables, List<JuanHaoTable> juanHaoTables, List<AccessoriesInfo> accessoriesInfos,List<ImportAndExportOfRawMaterials>raws)
        {

                if (SysInfo.GetInfo.own != "审核制")
                {
                    danju.zhuangtai = "已审核";
                }
                else
                {
                    danju.zhuangtai = "未审核";
                }
                danju.dh = 单据BLL.检查单号(danju.dh);
                Connect.dbcontext.Insertable(danju).ExecuteCommand ();
                ///保存到单据明细      
                foreach (var d in danjumingxitables.Where(x => x.Bianhao != null).ToList())
                {
                    d.danhao = danju.dh;
                }
                Connect.dbcontext.Insertable (danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()).ExecuteCommand ();
                
            ///保存卷号
            List < FahuoDan > fahuoDans = new List<FahuoDan>();
                foreach (var j in juanHaoTables)
                {
                    var madan = new FahuoDan()
                    {
                        bh = j.SampleNum,
                        pm = j.SampleName,
                        GG = j.guige,
                        gh = j.GangHao,
                        ys = j.yanse,
                        jh = j.JuanHao,
                        mis = j.biaoqianmishu.ToString(),
                        color = j.yanse,
                        Gangjuanhao = j.PiHao.ToString(),
                        dh = danju.dh,
                        rq = danju.rq.Date,
                    };
                    fahuoDans.Add(madan);
                }
                foreach(var juan in juanHaoTables )
                {
                    juan.state = 1;
                    juan.Danhao = danju.dh;
                }
                Connect.dbcontext.Updateable(juanHaoTables).ExecuteCommand();
                //JuanHaoTableService.UpdateJuanHaoTable(x => x.state == 1 && x.Danhao == danju.dh, juanHaoTables);
                Connect.dbcontext.Insertable<FahuoDan>(fahuoDans).ExecuteCommand();
                Connect.dbcontext.Insertable(raws).ExecuteCommand();
            Connect.dbcontext.Insertable(accessoriesInfos).ExecuteCommand();
            // FahuoDanService.InsertFahuoDanlst(fahuoDans);
            if (SysInfo.GetInfo.own != string.Empty)
                {
                    if (SysInfo.GetInfo.own != "审核制")
                    {
                        var danhao = danju.dh;
                        单据审核(danhao);
                    }
                }     
        }
        public static void 修改单据(DanjuTable danju, List<danjumingxitable> danjumingxitables, List<JuanHaoTable> juanHaoTables, List<AccessoriesInfo> accessoriesInfos, List<ImportAndExportOfRawMaterials> raws)
        {
            //删除信息
            if (SysInfo.GetInfo.own != string.Empty)
            {
                if (SysInfo.GetInfo.own != "审核制")
                {
                    var danhao = danju.dh;
                    单据反审核(danhao);
                }
            }
            ///删除原始单据信息
            Connect.dbcontext.Deleteable<danjumingxitable>().Where(x => x.danhao == danju.dh).ExecuteCommand();//删除单据明细
            Connect.dbcontext.Deleteable<FahuoDan >().Where(x => x.dh == danju.dh).ExecuteCommand();//删除发货单
            Connect.dbcontext.Deleteable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == danju.dh).ExecuteCommand();//删除原料信息
            Connect.dbcontext.Deleteable<AccessoriesInfo>().Where(x => x.danhao == danju.dh).ExecuteCommand();//删除底布信息
            //更新单据表
            Connect.dbcontext.Updateable(danju).ExecuteCommand();
            DeleteLogService.InsertDeleteLog(new DeleteLog() { date = DateTime.Now, Log = $"修改发货单号{danju.dh} 内容是" + JsonConvert.SerializeObject(danju), useID = Tools.CurrentUser.user.YHBH });
            Connect.dbcontext.Insertable(danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()).ExecuteCommand();//保存单据明细
            List<FahuoDan> fahuoDans = new List<FahuoDan>();
            foreach (var j in juanHaoTables)
            {
                var madan = new FahuoDan()
                {
                    bh = j.SampleNum,
                    pm = j.SampleName,
                    GG = j.guige,
                    gh = j.GangHao,
                    ys = j.yanse,
                    jh = j.JuanHao,
                    mis = j.biaoqianmishu.ToString(),
                    color = j.yanse,
                    Gangjuanhao = j.PiHao.ToString(),
                    dh = danju.dh,
                    rq = danju.rq.Date,
                };
                fahuoDans.Add(madan);
                j.state = 1;
                j.Danhao = danju.dh;
            }
            Connect.dbcontext .Updateable( juanHaoTables).ExecuteCommand ();
            Connect.dbcontext.Insertable(fahuoDans).ExecuteCommand();
            Connect.dbcontext.Insertable(accessoriesInfos).ExecuteCommand();//保存底布信息
            Connect.dbcontext.Insertable(raws).ExecuteCommand();//保存原料信息
            if (SysInfo.GetInfo.own != string.Empty)
                {
                    if (SysInfo.GetInfo.own != "审核制")
                    {
                        var danhao = danju.dh;
                        单据审核(danhao);
                    }
                }
        }
        public static void 删除单据(string deldanhao)
        {
            var danhao = deldanhao;
            if (SysInfo.GetInfo.own != string.Empty)
            {
                if (SysInfo.GetInfo.own != "审核制")
                {
                    单据反审核(danhao);
                }
            }
            Connect.dbcontext.Deleteable<danjumingxitable>().Where(x => x.danhao == danhao).ExecuteCommand();//删除单据明细
            Connect.dbcontext.Deleteable<FahuoDan>().Where(x => x.dh == danhao).ExecuteCommand();//删除发货单
            Connect.dbcontext.Deleteable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == danhao).ExecuteCommand();//删除原料信息
            Connect.dbcontext.Deleteable<AccessoriesInfo>().Where(x => x.danhao == danhao).ExecuteCommand();//删除底布信息
            Connect.dbcontext.Deleteable<DanjuTable>().Where(x => x.dh == danhao).ExecuteCommand();//删除单据明细
            //清除卷号状态
            Connect.dbcontext.Updateable<JuanHaoTable>().SetColumns(x=>new JuanHaoTable() { Danhao=string.Empty,state=0}).Where(x => x.Danhao == danhao).ExecuteCommand();//删除单据明细
           
            //var juans = JuanHaoTableService.GetJuanHaoTablelst(x => x.Danhao == danhao);
            //foreach (var juan in juans)
            //{
            //    juan.Danhao = "";
            //    juan.state = 0;
            //    JuanHaoTableService.UpdateJuanHaoTable(juan, x => x.JuanHao == juan.JuanHao);
            //}
        }
        public static List<danjumingxitable> GetFahuodanMingxi(string danhao)
        {
            return danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao);
        }
        public static string 单据审核(string danhao)
        {
            var danju = Connect.dbcontext.Queryable<DanjuTable >().First (x => x.dh == danhao);
            var danjumingxitables = Connect.dbcontext.Queryable<danjumingxitable >().Where (x => x.danhao == danhao).ToList ();
            var AccessoriesInfos = Connect.dbcontext.Queryable<AccessoriesInfo>().Where(x => x.danhao == danhao).ToList();
            var raws = Connect.dbcontext.Queryable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == danhao).ToList();
            var juanhaos = Connect.dbcontext.Queryable<JuanHaoTable>().Where (x => x.Danhao == danhao).ToList ();
            来往明细BLL.增加来往记录(danju);
            财务BLL.增加应收款(danju);
            财务BLL.增加应开发票(danjumingxitables, danju);
            架子BLL.架子出库(danjumingxitables, danju);
            if (danju.yaoqiu != "复合")
            {
                库存BLL.减少库存(danjumingxitables, danju);
            }
            库存BLL.减少库存(AccessoriesInfos, danju);
            库存BLL.原料出库(raws);
            单据BLL.审核(danhao);
            财务BLL.减少剩余额度(danju.ksbh, danju.je);
            增加发货数量(danjumingxitables);
            return "审核成功";
        }
        public static void 单据反审核(string danhao)
        {
             //回滚操作
             var danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao);
             var danjumingxitables = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao);
             var juanhaos = JuanHaoTableService.GetJuanHaoTablelst(x => x.Danhao == danhao);
            var AccessoriesInfos = Connect.GetSugar().Queryable<AccessoriesInfo>().Where(x => x.danhao == danhao).ToList();
            var raws = Connect.dbcontext.Queryable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == danhao).ToList();
            danju.zhuangtai = "未审核";
            Connect.dbcontext.Updateable(danju).ExecuteCommand();
             来往明细BLL.删除来往记录(danju);
             财务BLL.减少应收款(danju);
             财务BLL.减少应开发票(danju, danjumingxitables);
            //var rukumingxis = new List<danjumingxitable>();
            //for (int rowindex = 0; rowindex < danjumingxitables.Count; rowindex++)
            //{
            //    if (danjumingxitables[rowindex].IsDone == true)
            //    {
            //        var mingxi = danjumingxitables[rowindex];
            //        var rukumingxi = danjumingxitableService.GetOnedanjumingxitable(x => x.danhao == mingxi.rkdh && x.ganghao == mingxi.ganghao && x.yanse == mingxi.yanse);
            //        if (rukumingxi.pingming != string.Empty)
            //        {
            //            rukumingxi.offerid = danjumingxitables[rowindex].offerid;
            //            rukumingxi.suolv = danjumingxitables[rowindex].suolv;
            //            rukumingxis.Add(rukumingxi);
            //        }
            //    }
            //}
            if (danju.yaoqiu != "复合")
            {
                //库存BLL.增加库存(danjumingxitables.Where(x=>x.IsDone=false).ToList (), danju);
                库存BLL.增加库存(danjumingxitables, danju);
            }
             可发卷BLL.卷入库(danhao);
             架子BLL.架子入库 (danjumingxitables);
             架子BLL.删除日志(danhao); 
             财务BLL.增加剩余额度(danju.ksbh, danju.je);
             库存BLL.增加库存(AccessoriesInfos, danju);
            库存BLL.原料入库(raws);
            减少发货数量(danjumingxitables );
        }
        /// <summary>
        /// 检查销售出库单是否已经填写过该订单的其他费用
        /// </summary>
        /// <param name="OrderNum">订单号</param>
        /// <returns>已经收过返回True,没有返回False</returns>
        public static Boolean CheckDanjuMingxiContainOtherCost(string OrderNum)
        {
            var sql = $"select danjumingxitable.* from danjutable,danjumingxitable where danjutable.djlx='{DanjuLeiXing.销售出库单 }' and danjumingxitable.danhao=danjutable.dh and danjumingxitable.weishuiheji>0";
            var mingxis = danjumingxitableService.Getdanjumingxitablelst(sql);
            if (mingxis.Count > 0)
            {
                return true;
            }
            else
            { return false; }
        }
        public static void 增加发货数量(List<danjumingxitable > mingxis )
        {
            foreach(var m in mingxis )
            {
                var yanse = m.yanse.Split('/')[0];
                var ruku =  Connect.dbcontext .Queryable<danjumingxitable >().First (x=>x.danhao==m.rkdh &&x.pingming==m.pingming &&x.yanse==yanse &&x.ganghao ==m.ganghao  );
                if (ruku != null)
                {
                    ruku.toupimishu += m.toupimishu;
                    ruku.toupijuanshu += m.chengpingjuanshu;
                    ruku.InventoryQuantity -= m.toupimishu;
                    if (m.IsDone)
                    {
                        ruku.InventoryQuantity = 0;
                    }
                    CalculateShrinkage(ruku);
                    Connect.dbcontext.Updateable<danjumingxitable>(ruku).ExecuteCommand();
                }
            }
        }
        /// <summary>
        /// 计算缩率
        /// </summary>
        /// <param name="ruku"></param>
        public  static void CalculateShrinkage(danjumingxitable ruku)
        {          
                if ((ruku.chengpingmishu - ruku.ExitsNum - ruku.InventoryQuantity) != 0)
                {
                    ruku.suolv = ruku.chengpingmishu - ruku.ExitsNum - ruku.InventoryQuantity - ruku.toupimishu;
                }          
        }
        public static void 减少发货数量(List<danjumingxitable> mingxis)
        {
            foreach (var m in mingxis)
            {
                var yanse = m.yanse.Split('/')[0];
                var ruku = Connect.dbcontext.Queryable<danjumingxitable >().First (x => x.danhao == m.rkdh && x.pingming == m.pingming && x.yanse == yanse && x.ganghao == m.ganghao
               && x.kuanhao == m.kuanhao);
                if (ruku != null)
                {
                    ruku.toupimishu -= m.toupimishu;
                    ruku.toupijuanshu -= m.chengpingjuanshu;
                    if(ruku.IsDone)
                    {
                        ruku.InventoryQuantity = ruku.chengpingmishu;
                    }
                    else
                    {
                        ruku.InventoryQuantity += m.toupimishu;
                    }
                    if (ruku.chengpingmishu - ruku.ExitsNum - ruku.InventoryQuantity == 0)
                    {
                        ruku.suolv = 0;
                    }
                    else
                    {
                        CalculateShrinkage(ruku);
                    }
                    Connect.dbcontext.Updateable<danjumingxitable>(ruku).ExecuteCommand();
                }
            }
        }
    }
}
